package com.example.todolist.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.todolist.dao.TodoItemDAO;
import com.example.todolist.dto.TodoIndexParameter;
import com.example.todolist.dto.TodoParameter;
import com.example.todolist.entity.TodoItemModel;
import com.example.todolist.service.TodoItemService;
import org.apache.commons.lang3.Streams;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mybatis-generator
 * @since 2021-08-25
 */
@Service
public class TodoItemServiceImpl extends ServiceImpl<TodoItemDAO, TodoItemModel> implements TodoItemService {

    @Resource
    private TodoItemDAO todoItemDAO;


    @Override
    public TodoItemModel addTodoItem(TodoParameter todoParameter) {
        if (todoParameter == null) {
            throw new IllegalArgumentException("Null or empty content is not allowed");
        }

        final TodoItemModel item = new TodoItemModel(todoParameter.getContent());
        this.todoItemDAO.save(item);
        return item;
    }

    @Override
    public Optional<TodoItemModel> markTodoItemDone(TodoIndexParameter index) {
        final List<TodoItemModel> all = this.todoItemDAO.findAll();

        final Optional<TodoItemModel> optionalItem = StreamSupport.stream(all.spliterator(), false)
                .filter(element -> element.getId() == index.getIndex())
                .findFirst();
        return optionalItem.flatMap(this::doMarkAsDone);
    }

    private Optional<TodoItemModel> doMarkAsDone(final TodoItemModel todoItem) {
        todoItem.markDone();
        this.todoItemDAO.updateById(todoItem);
        return Optional.of(todoItem);
    }

    @Override
    public List<TodoItemModel> showList(boolean all) {
        return Streams.stream(this.todoItemDAO.findAll())
                .filter(item -> all || !item.getDone())
                .collect(Collectors.toList());
    }
}
